#!/bin/sh
#error and exit = set -e
#set -o errexit
#color
source /etc/init.d/functions
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'

function deal(){

  sudo sed -e 's|^mirrorlist=|#mirrorlist=|g' \
    -e 's|^#baseurl=http://mirror.centos.org/centos|baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos|g' \
    -i.bak \
    /etc/yum.repos.d/CentOS-*.repo
  sudo sed -e 's|^mirrorlist=|#mirrorlist=|g' \
    -e 's|^baseurl=http://mirror.centos.org/centos|baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos|g' \
    -i.bak \
    /etc/yum.repos.d/CentOS-*.repo
  yum install epel-release -y > /dev/null 2>&1
  sudo sed -e 's!^metalink=!#metalink=!g' \
    -e 's!^#baseurl=!baseurl=!g' \
    -e 's!https\?://download\.fedoraproject\.org/pub/epel!https://mirrors.tuna.tsinghua.edu.cn/epel!g' \
    -e 's!https\?://download\.example/pub/epel!https://mirrors.tuna.tsinghua.edu.cn/epel!g' \
    -i /etc/yum.repos.d/epel*.repo

}

function checkparam(){
  if [ $# -gt 0 ] ;then
    case $1 in
      "-f")
        return 1
        ;;
      "force")
        return 1
        ;;
      *)
        echo "vaild param is -f or force"
        exit -1
        ;;
    esac
  fi
}

function checkfile(){
  checkparam $*
  if [ $? -eq 1 ] ;then
    action "$0" deal
  else
    if [ -d /etc/yum.repos.d.bak ] ;then
      echo -e "${green}[$0] /etc/yum.repos.d.bak is exists. force update use param -f or force.${plain}"
      action "$0"
      return 0
    else
      action "$0" deal
    fi
  fi
}

function main(){
  checkfile $*
}

main $*
